package br.com.agiledev.webscrum.action;

import java.util.ArrayList;
import java.util.List;

import javax.faces.event.ActionEvent;

import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.FlushModeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;

import br.com.agiledev.webscrum.eao.ScrumRoleEAO;
import br.com.agiledev.webscrum.entity.ScrumRole;
import br.com.agiledev.webscrum.entity.Team;
import br.com.agiledev.webscrum.entity.User;

@SuppressWarnings("serial")
@Name("teamMB")
public class TeamAction extends HomeAction<Team> {

    @DataModelSelection
    ScrumRole scrumRole;
    
    @DataModel
    List<ScrumRole> componentes;
    
    @In
    ScrumRoleEAO scrumRoleEAO;
    
    @Factory("componentes")
    public void fabricaComponentes() {
	componentes = getInstance().getScrumRoles();
    }
    
    @Factory("team")
    public Team initTeam() {
	Team team = getInstance();
	
	if(team != null) {
	    if(team.getScrumRoles() == null || team.getScrumRoles().isEmpty()) {
        	team.setScrumRoles(new ArrayList<ScrumRole>());
        	
        	ScrumRole sr = new ScrumRole();
        	sr.setUser(new User());
        	sr.setTeam(team);
        	team.getScrumRoles().add(sr);
	    }
	}
	
	return team;
    }

    @Override
    public void setId(Object id) {
	super.setId(Long.valueOf(id.toString()));
    }

    @Begin(flushMode = FlushModeType.MANUAL)
    @Override
    public void create() {
	super.create();
    }
    
    @Override
    public String persist() {
        String retorno = super.persist();
        
/*        for (ScrumRole scrumRole : componentes) {
            if(scrumRole.getOid() == null) {
        	scrumRoleEAO.persist(scrumRole);
            }
            else {
        	scrumRoleEAO.merge(scrumRole);
            }
	}*/
        
        getEntityManager().flush();
        
        return retorno;
    }
    
    public void newComponent(ActionEvent event) {
	
	ScrumRole scrumRole = new ScrumRole(getInstance());
	scrumRole.setUser(new User());
	
	componentes.add(scrumRole);
    }    
    
    public void removeComponent(ActionEvent event) {
	System.out.println(scrumRole);
    }

    public void persistComponent(ActionEvent event) {
	System.out.println(scrumRole);
    }
}